﻿using Common;

namespace yongGu
{
    public class PullStockOutTask
    {
        public void GetStockOutFromErp()
        {
            while (true)
            {
                try
                {
                    Config.Logger.Information("出库任务开始记录");
                    DataAccess ds = new DataAccess();
                    var stockOut = ds.GetStockOut();
                    var c = Convert(stockOut);
                    foreach (var r in c)
                    {
                        PostToHY(r);
                    }
                    if (c.Count > 0)
                        Config.Logger.Information("成功出库{0}笔记录", c.Count);
                }
                catch (Exception ex)
                {
                    Config.Logger.Error(ex.StackTrace + "\r\n" + ex.Message);
                }
                finally 
                {
                    Config.Logger.Information("出库睡眠30秒");
                    Thread.Sleep(30 * 1000);

                }
            }
        }
        private List<RecordOutModel> Convert(List<StockOutModel> stock)
        {
            List<RecordOutModel> result = new List<RecordOutModel>();
            foreach (var item in stock)
            {
                var record = result.FirstOrDefault(r => r.orderNo == item.FBillNo);
                if (record == null)
                {
                    record = new RecordOutModel();
                    record._type = item.Type;
                    record.ksSaleOrderDetailDTOS = new List<RecordOutDetailModel>();
                    record.orderNo = item.FBillNo;
                    record.customerAddress = item.Address;
                    record.customerName = item.CustomerName;
                    result.Add(record);
                }
                record.ksSaleOrderDetailDTOS.Add(new RecordOutDetailModel()
                {
                    qtyRequired = (int)item.FRealQty,
                    skuCode = item.FNumber,
                    skuName = item.FName
                });
            }
            return result;
        }

        private void PostToHY(RecordOutModel recordmodel)
        {
            HttpHelper httpHelper = new HttpHelper();
            DataAccess ds = new DataAccess();
            try
            {
                var r = httpHelper.Post<ResponseFromWMS, RecordOutModel>(Config.WMS_URL + "/adapter/api/haiq?api=HAIQ_WMS_SHIPMENT_CREATE", recordmodel);
                Console.WriteLine(r.code);
                ds.SetOutResult(recordmodel.orderNo, r.code, r.message,recordmodel._type);
            }
            catch (Exception ex)
            {
                ds.SetOutResult(recordmodel.orderNo, -99, ex.Message, recordmodel._type);
                Config.Logger.Error(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
    }
}
